// 引入vuerouter的相关包
import {
  createWebHashHistory,
  createWebHistory,
  createRouter,
} from 'vue-router'
import { createDiscreteApi } from 'naive-ui'
import { storeToRefs } from 'pinia'
import { mainData } from '@/stores/index'

// 路由加载进度
const { loadingBar } = createDiscreteApi(['loadingBar'])

// 创建实例化对象
// const history = createWebHashHistory()
const history = createWebHistory()
const router = createRouter({
  history,
  routes: [
    {
      name: '登录页',
      path: '/login',
      component: () => import('@/views/LoginView/LoginView.vue'),
    },
    {
      name: '页面不存在',
      path: '/404',
      component: () => import('@/views/ResultView/NoView/NoView.vue'),
    },
    {
      name: '服务器错误',
      path: '/500',
      component: () => import('@/views/ResultView/ErrorView/ErrorView.vue'),
    },
    {
      name: '页面禁止访问',
      path: '/403',
      component: () =>
        import('@/views/ResultView/ProhibitedView/ProhibitedView.vue'),
    },
    {
      name: '主体',
      path: '/',
      redirect: '/work',
      component: () => import('@/views/MainView/MainView.vue'),
      children: [
        {
          name: '工作台',
          path: '/work',
          component: () => import('@/views/WorkView/WorkView.vue'),
        },
        {
          name: '用户管理',
          path: '/users',
          component: () => import('@/views/SystemView/UsersView/UsersView.vue'),
        },
      ],
    },
  ],
})

function ifRouter(path) {
  let rout = router.options.routes[4].children
  rout.map((item) => {
    if (item.path != path) {
      router.push('/404')
    }
  })
}

// 导航守卫
router.beforeEach((to, from, next) => {
  let piniaData = mainData()
  let { ifUserAuthority } = storeToRefs(piniaData)
  loadingBar.start()

  // 权限校验流程
  if (
    ifUserAuthority.value != null &&
    ifUserAuthority.value != undefined &&
    ifUserAuthority.value != true
  ) {
    console.log('????')
    // console.log(ifUserAuthority.value);
    ifUserAuthority.value = true
    // console.log(to.path);
    next()
  } else {
    // ifRouter(to.path)
    console.log('/？？？？')
    // console.log(to.path);
    next()
  }
})

// 设置后置路由守卫
router.afterEach((to, from, next) => {
  // 路由中导入-结束
  loadingBar.finish()
})

// 把router路径暴露出去
export default router
